<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class MOauthController
extends MApplicationComponent
implements MIController
{
    
    public function invoke($uri=null)
    {
                                parent::init();

        $server = new MOauthServerDecide();
        $path = explode('?', $uri);
        $parts = array_slice(explode('/', $path[0]), 2);

        if ($parts[0] === "request_token") {
            $server->requestToken();
        }
        elseif ($parts[0] === "access_token") {
            $server->accessToken();
        }
        elseif ($parts[0] === "authorize") {
                        $device = self::judge_device();
            if ($device != false){
                try
                {
                    $_SESSION['authorized'] = true;
                    $server->authorizeVerify();
                    $server->authorizeFinish(true, $device->id);
                }
                catch (OAuthException2 $e)
                {
                    $error = "Failed OAuth Request: " . $e->getMessage();
                    throw new MAuthorizationException($error, 401);
                }
            }else{
                $error = "Failed OAuth Request :User authentication fail";
                throw new MAuthorizationException($error, 401);
            }
        }
    }


    
    private function judge_device()
    {
        $device_type  = $_REQUEST['device_type'];
        $device_name  = urldecode($_REQUEST['device_name']);
        $device_info  = $_REQUEST['device_info'];

        if (!empty($device_type) && !empty($device_name) && !empty($device_info)){
        } else {
                        if (empty($device_type) && empty($device_name) && empty($device_info)){
                $device_type = 10;
                $device_name = "第三方用户";
                $device_info = "第三方设备";
            }else{
                throw new MAuthorizationException("param_is_null", MConst::HTTP_CODE_400);
            }
        }

        $user = self::search_user();
        if ($user === false){
            return false;
        }

        if ($user->user_status  == 0){
            throw new MAuthorizationException("User has disabled.", MConst::HTTP_CODE_407);
        }

        $user_id = $user->id;

        $device_uuid = MUtils::getDeviceUUID($device_info, $device_type, $device_name, $user_id);
        $device = new MUserDevice();
        $device_query = $device->queryUserDeviceByDevceUUID($device_uuid);

                if ($device_query === false) {
            $device->addUserDevices($user_id, $device_uuid, $device_type, $device_info, $device_name);
            $device->queryUserDeviceByDevceUUID($device_uuid);
        }

        return $device;
    }


    
    private function search_user()
    {
        $user_name    = urldecode($_REQUEST['user_name']);
        $password     = $_REQUEST['password'];
        $requestToken = $_REQUEST['oauth_token'];

        if (empty($user_name) || empty($password) || empty($requestToken))
        {
            FXP::trace(FXP::t("用户名或者密码为空"));
            return false;
        }
                $key          = substr($requestToken, 0, 8);

                $user = $this->validUser($key, $user_name, $password);
        if ($user){
            return MUser::initUser($user);
        }

                                                                                                                                                        return false;
    }

    
    private function validUser($key, $user_name, $ciphertext){
                $plaintext    = MSecret::decryptHex($key, $ciphertext);

                $uerObject = new CUserValid();
        $user = $uerObject->validUser($user_name, $plaintext);
        if(!isset($user) || !$user){
            return false;
        }
        return $user;
    }

    
    private function ret_error($message){
        header('HTTP/1.1 400 Bad Request');
        header('Content-Type: text/plain');
         
        echo $message;
    }
}
?>